package com.irdstudio.efp.esb.api.rest.yx;

import java.util.Date;
import java.util.Objects;

import javax.servlet.http.HttpServletRequest;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.ModelAttribute;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.irdstudio.basic.framework.core.constant.BaseConstant;
import com.irdstudio.basic.framework.core.exception.BizException;
import com.irdstudio.efp.esb.api.bean.yx.ReqBraQueryBean;
import com.irdstudio.efp.esb.api.bean.yx.RespBraQueryBean;
import com.irdstudio.efp.esb.api.common.EsbRespServiceBeanCreator;
import com.irdstudio.efp.esb.api.common.TransactionTypeEnum;
import com.irdstudio.efp.esb.common.constant.EsbBizEnums;
import com.irdstudio.efp.esb.common.constant.EsbSysHeadEnums;
import com.irdstudio.efp.esb.common.server.req.EsbReqServiceBean;
import com.irdstudio.efp.esb.common.server.resp.EsbRespServiceBean;
import com.irdstudio.efp.nls.service.facade.NlsApplyInfoService;
import com.irdstudio.efp.nls.service.vo.NlsApplyInfoVO;

/**
 * 网贷用查询接口
  * @author heyingfeng
  * @since 2019年3月4日 下午2:52:38
  * @version 1.0
 */
@RestController
@RequestMapping("/esb")
public class BraQueryController {
	private static Logger logger = LoggerFactory.getLogger(BraQueryController.class);

	/**
	 * 获取ESB请求对象，校验 ESB请求系统头和请求应用头对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:28:08
	 * @version 1.0
	 */
	@ModelAttribute("esbReqServiceBean")
	public EsbReqServiceBean getReqEsbHeadBean(HttpServletRequest request) {
		logger.info("校验 ESB请求系统头和请求应用头对象!");
		EsbReqServiceBean esbReqServiceBean = (EsbReqServiceBean) request.getAttribute("esbReqServiceBean");
		return esbReqServiceBean;
	}

	/**
	 * 获取ESB请求对象，校验 ESB请求体对象
	 * 
	 * @param request
	 *            请求对象集合
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:31:14
	 * @version 1.0
	 */
	@ModelAttribute("reqBraQueryBean")
	public ReqBraQueryBean getReqEsbBodyBean(HttpServletRequest request) {
		logger.info("校验 ESB请求体对象！");
		String esbReqBody = (String) request.getAttribute("esbReqBody");
		return JSONObject.parseObject(esbReqBody, ReqBraQueryBean.class);
	}

	/**
	 * 1.通过切面校验进件申请参数是否正确，如不正确则返回错误信息<br>
	 * 2.调用对应的中台服务<br>
	 * 3.增加调用队列任务表信息<br>
	 * TODO:此处为统一的进件交易，先暂时不按照产品代码进行划分，后续根据差异化需求决定是否拆分；
	 * 
	 * @param esbReqServiceBean
	 *            ESB请求对象
	 * @param br1
	 * @param reqCreditBean
	 *            ESB请求体的对象
	 * @param br2
	 * @param exception
	 *            切面的异常信息
	 * @return
	 * @throws Exception
	 * @author huangwb
	 * @since 2019年1月20日 下午2:20:51
	 * @version 1.0
	 */
	@PostMapping("/SERVICE_30230005_02")
	public EsbRespServiceBean doRecv(@Validated @ModelAttribute("esbReqServiceBean") EsbReqServiceBean esbReqServiceBean, BindingResult br1,
			@Validated @ModelAttribute("reqBraQueryBean") ReqBraQueryBean reqBraQueryBean, BindingResult br2, Exception exception) throws Exception {
		String reqSn = reqBraQueryBean.getAppFlowNo();//流水号
		String channelNo = reqBraQueryBean.getChanFlg();//渠道
		String baiduSnId = reqBraQueryBean.getBaiduSnId(); //会话ID
		String evID = reqBraQueryBean.getEvID(); //事务ID
		NlsApplyInfoVO nlsApplyInfoVO = new NlsApplyInfoVO();
		try {
			// 通过切面校验进件申请参数是否正确，如不正确则返回错误信息
			if (Objects.nonNull(exception)) {
				throw exception;
			}
			// TODO applSeq是否与用信关联
			if("05".equals(channelNo)) {//度小满
				nlsApplyInfoVO.setBdReqSn(reqSn);
				nlsApplyInfoVO = nlsApplyInfoService.queryByPk(nlsApplyInfoVO);
				if (nlsApplyInfoVO == null) {
					throw new BizException("无用信数据");
				}
				return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
						JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), "查询成功", nlsApplyInfoVO)), //
						EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
						EsbBizEnums.RetCodeEnum.SUCCESS.getVALUE(), //
						"查询成功");
			}
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), "非百度渠道", nlsApplyInfoVO)), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
					"非百度渠道");
		} catch (BizException e) {
			logger.error("用信查询服务接口处理成功!" + e.getMessage());
			e.printStackTrace();
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), e.getMessage(), nlsApplyInfoVO)), //
					EsbSysHeadEnums.RetStEnum.SUCCESS.getCode(), //
					EsbBizEnums.RetCodeEnum.YWLJCLYC.getVALUE(), //
					e.getMessage());
		} catch (Exception e) {
			logger.error("用信查询服务接口处理失败!" + e.getMessage());
			e.printStackTrace();
			return EsbRespServiceBeanCreator.buildesbRespServiceBean(esbReqServiceBean, //
					JSON.toJSONString(buildRespCreditBean(baiduSnId,evID,EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), e.getMessage(), nlsApplyInfoVO)), //
					EsbSysHeadEnums.RetStEnum.FAILURE.getCode(), //
					EsbBizEnums.RetCodeEnum.OTHERS_EXCEPTION.getVALUE(), //
					e.getMessage());
		}
	}

	/**
	 * 组织用户借款请求接口的返回对象
	 * 
	 * @param retStCd
	 *            返回状态码
	 * @param retMsg
	 *            返回信息
	 * @return
	 * @author huangwb
	 * @since 2019年1月20日 下午1:59:46
	 * @version 1.0
	 * @throws BizException 
	 */
	private RespBraQueryBean buildRespCreditBean(String baiduSnId,String evID,String retCd, String retMsg, NlsApplyInfoVO nlsApplyInfoVO) throws BizException {
		RespBraQueryBean respBraQueryBean = new RespBraQueryBean();
		try {
			respBraQueryBean.setRetCd(retCd);
			respBraQueryBean.setRetMsg(retMsg);
			if(EsbBizEnums.RetCodeEnum.SUCCESS.VALUE.equals(retCd)) {
				respBraQueryBean.setRetStCd(nlsApplyInfoVO.getNlsApplyState());//01：处理中 02：通过 03：拒绝 04：取消 05：挂起 06：审批作废
				if(!BaseConstant.NLS_APPLY_STATE_02.equals(nlsApplyInfoVO.getNlsApplyState()) &&
						!BaseConstant.NLS_APPLY_STATE_01.equals(nlsApplyInfoVO.getNlsApplyState())) {//不通过
					respBraQueryBean.setbDRsnCd(nlsApplyInfoVO.getBdReasonCode());//百度原因码
					respBraQueryBean.setbDRsnCdDsc(nlsApplyInfoVO.getBdReasonMsg());//原因码描述
				}
				respBraQueryBean.setEvTp(TransactionTypeEnum.TRANSACTION.getValue());//事务类型
				respBraQueryBean.setEvID(evID);//事务ID
				respBraQueryBean.setBaiduSnId(baiduSnId);//会话ID
				respBraQueryBean.setTxnTmstmp(new Date().getTime()+"");//时间戳
				respBraQueryBean.setCertNo(nlsApplyInfoVO.getCertCode());//证件码
				respBraQueryBean.setBankCardNo(nlsApplyInfoVO.getRecvAcctNo());//银行卡
				respBraQueryBean.setCustNm(nlsApplyInfoVO.getCusName());//客户姓名
				respBraQueryBean.setMblNo(nlsApplyInfoVO.getMobile());//手机号
			}
		} catch (Exception e) {
			logger.error(e.getMessage());
			throw new BizException("数据异常");
		}
		return respBraQueryBean;
	}

	@Autowired
	@Qualifier("nlsApplyInfoService")
	private NlsApplyInfoService nlsApplyInfoService;
}
